package cn.sstech.IM.webserver.user.service.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.protobuf.InvalidProtocolBufferException;

import cn.sstech.IM.constant.Constants;
import cn.sstech.IM.server.group.ImChannelGroup;
import cn.sstech.IM.server.model.MessageWrapper;
import cn.sstech.IM.server.model.proto.MessageBodyProto;
import cn.sstech.IM.server.model.proto.MessageProto;
import cn.sstech.IM.util.result.DefaultResult;
import cn.sstech.IM.util.result.IBaseResult;
import cn.sstech.IM.util.result.RetResultCode;
import cn.sstech.IM.webserver.user.dao.SuperManagerDao;
import cn.sstech.IM.webserver.user.model.UserAccountEntity;
import cn.sstech.IM.webserver.user.service.SuperManagerService;

@Service
public class SuperManagerServiceImpl implements SuperManagerService{

	@Autowired
	SuperManagerDao superManagerDao;
	
	Logger logger = LoggerFactory.getLogger(SuperManagerServiceImpl.class);
	
	@Override
	public IBaseResult broadcast(UserAccountEntity currentUser, String msgContent) {
		Long userId = currentUser.getUserInfo().getId();
         
         
		Integer isSuperManager = superManagerDao.checkIsSuperManager(userId);
		if(null != isSuperManager && isSuperManager>0){
			MessageProto.Model.Builder builder = MessageProto.Model.newBuilder();
	        builder.setCmd(Constants.CmdType.MESSAGE);
	        builder.setSender(currentUser.getId().toString());
	        builder.setTimeStamp(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
	        builder.setMsgtype(Constants.ProtobufType.SEND);
	        MessageBodyProto.MessageBody.Builder  msg =  MessageBodyProto.MessageBody.newBuilder();
	        msg.setContent(msgContent); 
	        builder.setContent(msg.build().toByteString());
	        

			  try {
				  MessageProto.Model message =  MessageProto.Model.parseFrom(builder.build().toByteArray());
		        MessageWrapper wrapper = new MessageWrapper(MessageWrapper.MessageProtocol.GROUP, currentUser.getId().toString(), null,message);
		         
		         ImChannelGroup.broadcast(wrapper.getBody());
			} catch (InvalidProtocolBufferException e) {
				logger.error(e.getMessage(),e);
			}
		}
		else{
			return DefaultResult.buildFailedResult(RetResultCode.E10004);
		}
		
		return DefaultResult.buildSuccessResult();
	}

}
